import { ref, nextTick } from 'vue';
import { ILayout } from './form.types';
import { message } from 'ant-design-vue';

export const useForm = (form: Record<string, any>, plot: ILayout = { label: 5 }) => {
    /**表单model */
    const formState = ref<any>({})
    /**表单对象ref */
    const formRef = ref()
    //布局
    const layout = {
        labelCol: { span: plot.label },
        wrapperCol: { span: 24 - plot.label },
    };
    //加载
    let loading:any

    const showLoading = () => {
        loading = message.loading('提交信息', 0)
    }
    const hideLoading = () => {
        setTimeout(loading,100)
    }
    /**
   * @method 设置表单数据
   * @param data 需要设置的数据
   * @returns  void
   */
    function setFormStateData() {
        Object.assign(formState.value, form)
    }
    onMounted(() => {
        setFormStateData()
    })
    /**
   * @method 表单校验
   * @returns  Promise<Record<string, any> | ValidateErrorEntity>
   */
    async function formValidateFields(): Promise<Record<string, any>> {
        return new Promise<Record<string, any>>(async (resolve, reject) => {
            try {
                await formRef.value?.validateFields()
                resolve(formState.value)
            } catch (error: any) {
                reject(error)
            }
        })
    }

    /**
   * @method 移除表单项的校验结果。传入待移除的表单项的 name 属性或者 name 组成的数组，如不传则移除整个表单的校验结果
   * @param nameList 表单对应的name字段组成的数组
   * @returns void
   */
    function clearValidate(nameList?: string | (string | number)[]) {
        if (!nameList) {
            nextTick(() => {
                formRef.value?.clearValidate()
                return
            })
        }
        if (nameList?.length) {
            if (!Array.isArray(nameList)) {
                throw new Error('移除表单校验的name必须为一个数组')
            } else {
                formRef.value?.clearValidate(nameList)
            }
        }
    }

    /**
     * @method 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
     * @param nameList 表单对应的name字段组成的数组
     * @returns void
     */
    function resetFields(nameList?: string | (string | number)[]) {
        if (!nameList) {
            formRef.value?.resetFields()
            return
        }
        if (nameList?.length) {
            if (!Array.isArray(nameList)) {
                throw new Error('重置的name必须为一个数组')
            } else {
                formRef.value?.resetFields(nameList)
            }
        }
    }

    return {
        formState,
        formRef,
        layout,
        showLoading,
        hideLoading,
        formValidateFields,
        clearValidate,
        resetFields
    }
}